package com.fita.wechat.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.demo2do.core.entity.exception.BusinessException;
import com.demo2do.core.persistence.GenericDaoSupport;
import com.fita.entity.order.Order;
import com.fita.entity.order.OrderPayType;
import com.fita.entity.order.PaymentRequest;
import com.fita.wechat.service.PaymentCallbackService;

/**
 * 
 * @author mohanlan
 *
 */
@Service("paymentCallbackService")
public class PaymentCallbackServieImpl implements PaymentCallbackService {
    
    @Autowired
    private GenericDaoSupport genericDaoSupport;
    
    /*
     * (non-Javadoc)
     * @see com.fita.wechat.service.PaymentCallbackService#load(java.lang.String)
     */
    public PaymentRequest load(String requestCode) {
        return genericDaoSupport.searchForObject("FROM PaymentRequest WHERE code = :code AND disabled = false AND payCode IS NULL AND payTime IS NULL", "code", requestCode, PaymentRequest.class);
    }
    
    @Override
    public Order pay(PaymentRequest paymentRequest, String orderCode, String payCode,
            String payTime, int amount) {
        
        Order order = this.loadOrder(orderCode);
        
        if(order == null) {
            throw new BusinessException("支付回调订单数据有误");
        }
        
        // 1. update payment request
        genericDaoSupport.update(paymentRequest.paid(payCode));
        
        // 2. update recharge order
        // FIXME here order pay type
        genericDaoSupport.update(order.paid(amount, OrderPayType.WECHAT));
        
        return order;
    }
    
    /**
     * 
     * @param code
     * @return
     */
    private Order loadOrder(String code) {
        return genericDaoSupport.searchForObject("FROM Order WHERE disabled = false AND payStatus = 'UNPAID' AND code = :code", "code", code, Order.class);
    }
    
}
